/* Orbas:
 *     A open source CORBA Specification implementation from Huihoo.
 *
 * Copyright 2002-2003 Huihoo.org, Inc. All Right Reserved.
 *
 * This software is licensed under LGPL license.
 * See terms of license at gnu.org.
 *
 * For more information, visit:
 *
 * http://www.huihoo.org/orbas
 */

package org.huihoo.orbas.orb.protocols.iiop;

/**
 * <p>Description: </p>
 * TCP connections.
 * <p>Copyright (c) 2002,2003</p>
 * <p>Company: <a href="http://www.huihoo.org/">huihoo.org</a></p>
 * @author <a href="http://www.huihoo.org/~mep">mep(mep@huihoo.com)</a>
 * @see <a href="http://www.huihoo.org/orbas">http://www.huihoo.org/orbas</a>
 * @version 1.0
 */

import org.huihoo.orbas.orb.protocols.Channel;
import org.huihoo.orbas.orb.protocols.TargetAddress;
import org.huihoo.orbas.orb.protocols.Transport;

public class IiopChannel extends Channel implements java.lang.Runnable {

	private IiopTargetAddress address;
	java.net.ServerSocket serverSock;

	public IiopChannel() {

	}

	public int getProtocolTag() {
		return org.omg.IOP.TAG_INTERNET_IOP.value;
	}

	public TargetAddress getTargetAddress() {
		return address;
	}

	public void setServerPort(int port) throws java.io.IOException {
		// try {
		serverSock = new java.net.ServerSocket(port);
		// }W
		// catch(java.net.BindException ex) {
		//
		// }
		// catch(java.io.IOException e) {
		// System.out.println("Cannot create server socket.");
		// e.printStackTrace();
		// }
	}

	public int getServerPort() {
		return serverSock.getLocalPort();
	}

	public void setTargetAddress(TargetAddress a) {
		address = (IiopTargetAddress) a;
	}

	public Transport setup() {
		try {

			java.net.Socket sock = new java.net.Socket(address.getHost(),
					address.getPort());

			return new IiopTransport(this, sock, address);
		} catch (java.io.IOException ioex) {
			System.out.println(ioex.toString());

		}

		return null;
	}

	public void teardown() {

	}

	public void run() {

	}

	public Transport accept() {

		java.net.Socket sock = null;

		try {
			sock = serverSock.accept();
			return new IiopTransport(null, sock, null);

		} catch (java.io.IOException e) {
			// If the Acceptor has not been shutdown
			System.out.println("Server Socket IO Exception" + e);
			return null;
		}
	}
}